package fr.sedoo.commons.server.storedfile.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.sedoo.commons.client.util.ListUtil;
import fr.sedoo.commons.shared.domain.StoredFile;

@Repository
public class StoredFileDAOJPAImpl implements StoredFileDAO {

	protected EntityManager em;

	public EntityManager getEntityManager() {
		return em;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Transactional
	public StoredFile save(StoredFile storedFile) {
		if (storedFile.getId() == null) {
			getEntityManager().persist(storedFile);
			return storedFile;
		} else {
			getEntityManager().merge(storedFile);
			return storedFile;
		}
	}

	@Override
	@Transactional
	public void deleteStoredFileByAttacherUuid(String attacherUuid) {
		List<StoredFile> list = em.createQuery("select storedFile from StoredFile storedFile where storedFile.attacherUuid='" + attacherUuid + "'").getResultList();
		for (StoredFile storedFile : list) {
			em.remove(storedFile);
		}
	}

	@Override
	public StoredFile findByAttacherUuid(String attacherUuid) {
		List<StoredFile> list = em.createQuery("select storedFile from StoredFile storedFile where storedFile.attacherUuid='" + attacherUuid + "'").getResultList();
		if ((list == null) || list.isEmpty()) {
			return new StoredFile();
		} else {
			return list.get(ListUtil.FIRST_INDEX);
		}
	}

}